﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MyGIS;
using static MyGIS.GISMyFile;

namespace test11
{
    public partial class Form1 : Form
    {
        GISDocument Document = new GISDocument();
        GISView View = null;
        Dictionary<GISLayer, ShowAttribute> AllAttwindows = new Dictionary<GISLayer, ShowAttribute>();
        Bitmap BackWindow;

        public Form1()
        {
            InitializeComponent();
        }

        private void OpenFileButton_Click(object sender, EventArgs e)
        {
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "Shapefile 文件|*.shp";//文件类型限制为Shapefile
            //openFileDialog.RestoreDirectory = false;//不还原选择文件时更改的目录
            //openFileDialog.FilterIndex = 1;
            //openFileDialog.Multiselect = false;//不允许同时选中多个文件
            //if (openFileDialog.ShowDialog() != DialogResult.OK) return;
            //Layer = GISShapefile.ReadShapefile(openFileDialog.FileName);
            //Layer.DrawAttributeOrNot = false;
            //MessageBox.Show("read" + Layer.FeatureCount() + "objects.");
            //View.UpdateExtent(Layer.Extent);
            //UpdateMap();
        }

        private void ShowMapButton_Click(object sender, EventArgs e)
        {
            //if (Layer == null)
            //{
            //    MessageBox.Show("目前没有加载图层，无法更新");
            //}
            //else
            //{
            //    View.UpdateExtent(Layer.Extent);
            //    UpdateMap();
            //}
        }


        /// <summary>
        /// 更新地图
        /// </summary>
        internal void UpdateMap()
        {
            if (View == null)
            {
                if (Document.IsEmpty())
                    return;
                View = new GISView(new GISExtent(Document.extent), ClientRectangle);
            }
            if (ClientRectangle.Width * ClientRectangle.Height == 0)//如果窗体最小化则不绘制
                return;
            View.UpdateRectangle(ClientRectangle);//更新当前View的窗口尺寸
            if (BackWindow != null)//根据最新的地图窗口尺寸建立背景窗口
                BackWindow.Dispose();
            BackWindow = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
            Graphics g = Graphics.FromImage(BackWindow);//在背景窗口上绘图
            g.FillRectangle(new SolidBrush(Color.Black), ClientRectangle);
            Document.Draw(g, View);
            Graphics graphics = CreateGraphics();//把背景窗口内容复制到到前景窗口上
            graphics.DrawImage(BackWindow, 0, 0);
            UpdateStatusBar();
        }


        private void MapButtonClick(object sender, EventArgs e)
        {
            GISMapActions actions = GISMapActions.zoomin;
            if ((Button)sender == ZoomInButton) actions = GISMapActions.zoomin;
            else if ((Button)sender == ZoomOutButton) actions = GISMapActions.zoomout;
            else if ((Button)sender == MoveDownButton) actions = GISMapActions.movedown;
            else if ((Button)sender == MoveUpButton) actions = GISMapActions.moveup;
            else if ((Button)sender == MoveLeftButton) actions = GISMapActions.moveleft;
            else if ((Button)sender == MoveRightButton) actions = GISMapActions.moveright;
            View.ChangeView(actions);
            UpdateMap();
        }

        /// <summary>
        /// 更改缩放系数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZoomingFactorBox_ValueChanged(object sender, EventArgs e)
        {
            //Layer.Extent.ZoomingFactor = (double)ZoomingFactorBox.Value;
        }
        private void MovingFactorBox_ValueChanged(object sender, EventArgs e)
        {
            //Layer.Extent.MovingFactor = (double)MovingFactorBox.Value;
        }



        /// <summary>
        /// 打开属性表按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void OpenTableButton_Click(object sender, EventArgs e)
        //{
        //    OpenAttributeWindow();
        //}
        public void OpenAttributeWindow(GISLayer layer)
        {
            ShowAttribute AttributeWindow = null;
            //若属性窗口已存在，就移除记录，稍后统一添加
            if (AllAttwindows.ContainsKey(layer))
            {
                AttributeWindow = AllAttwindows[layer];
                AllAttwindows.Remove(layer);
            }
            //初始化属性窗口
            if (AttributeWindow == null)
                AttributeWindow = new ShowAttribute(layer, this);
            if (AttributeWindow.IsDisposed)//若属性窗口资源被释放
                AttributeWindow = new ShowAttribute(layer, this);
            //添加属性窗口与图层的关联记录
            AllAttwindows.Add(layer, AttributeWindow);
            AttributeWindow.Show();//显示属性窗口
            if (AttributeWindow.WindowState == FormWindowState.Minimized)//若属性窗口最小化
                AttributeWindow.WindowState = FormWindowState.Normal;
            AttributeWindow.BringToFront();//把属性窗口放到最前端展示
        }



        private void SaveFileButton_Click(object sender, EventArgs e)
        {
            //WriteFile(Layer, @"D:\VS2019\MyGISFile\mygisfile.rcx");
            //MessageBox.Show("done");
        }

        private void ReadFileButton_Click(object sender, EventArgs e)
        {
            //Layer = ReadFile(@"D:\VS2019\MyGISFile\mygisfile.rcx");
            //MessageBox.Show("read" + Layer.FeatureCount() + "objects");
            //View.UpdateExtent(Layer.Extent);
            //UpdateMap();
        }


        /// <summary>
        /// 点选空间对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (Document.IsEmpty())
                    return;
                GISLayer Layer = Document.GetLayer(Document.layers[0].Name.ToString());
                if (Layer == null) return;
                GISVertex v = View.ToMapVertex(new Point(e.X, e.Y));
                SelectResult sr = Layer.Select(v, View);
                GISSelect gs = new GISSelect();
                gs.Select(v, Layer.GetAllFeatures(), Layer.ShapeType, View);
                if (sr == SelectResult.OK)//if(选中空间对象)
                {
                    if (Layer.ShapeType == GISShapefile.SHAPETYPE.poloygon)
                        //MessageBox.Show(gs.SelectedFeatures[0].GetAttribute(0).ToString());
                        MessageBox.Show(gs.SelectedFeatures[0].GetAttribute(0).ToString() + "\nx:" + gs.SelectedFeatures[0].spatialpart.centroid.x.ToString() +
                            " y:" + gs.SelectedFeatures[0].spatialpart.centroid.y.ToString());
                    else
                        //MessageBox.Show(gs.SelectedFeature.GetAttribute(0).ToString());//显示第一字段属性值
                        MessageBox.Show(gs.SelectedFeature.GetAttribute(0).ToString() + "\nx:" + gs.SelectedFeature.spatialpart.centroid.x.ToString() +
                            " y:" + gs.SelectedFeature.spatialpart.centroid.y.ToString());
                    UpdateMap();
                    UpdateAttributeWindow();
                }
            }

            //右键打开快捷菜单
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(this.PointToScreen(new Point(e.X, e.Y)));
            }

        }

        private void ClearSelectionButton_Click(object sender, EventArgs e)
        {
            //if (Layer == null)
            //    return;
            //Layer.ClearSelection();
            //UpdateMap();
            //SelectedFeaturesCount.Text = "已选中的空间对象的个数为0";
            //UpdateAttributeWindow();
        }


        /// <summary>
        /// 使地图大小适应窗口大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Resize(object sender, EventArgs e)//存在bug：更改窗口大小时还需要点击“显示全图”
        {
            if (View != null)
            {
                UpdateMap();
            }
        }



        /// <summary>
        /// 更新属性表窗口
        /// </summary>
        private void UpdateAttributeWindow()
        {
            if (Document.IsEmpty())
                return;
            foreach (ShowAttribute AttributeWindow in AllAttwindows.Values)
            {
                if (AttributeWindow == null)
                    continue;
                if (AttributeWindow.IsDisposed)//属性窗口资源已被释放
                    continue;
                AttributeWindow.UpdateData();
            }
        }


        /// <summary>
        /// 更新状态栏信息
        /// </summary>
        public void UpdateStatusBar()
        {
            SelectedFeaturesCount.Text = "当前地图文档中的图层数量为：" + Document.layers.Count.ToString();
        }



        /// <summary>
        /// 重绘窗体，解决最小化后内容消失的问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (View != null)
            {
                if (BackWindow != null)
                    e.Graphics.DrawImage(BackWindow, 0, 0);
            }
        }








        private void layerControlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayerControler LayerControl = new LayerControler(Document, this);
            LayerControl.Show();
        }
        private void openDocumentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "GIS Document" +"|*." + GISConst.MYDOC;
            openFileDialog.RestoreDirectory = false;
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;
            if (openFileDialog.ShowDialog() != DialogResult.OK)
                return;
            Document.Read(openFileDialog.FileName);
            if (Document.IsEmpty() == false)
                UpdateMap();
        }

        private void fullExtentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Document.IsEmpty() || View == null)
                return;
            View.UpdateExtent(Document.extent);
            UpdateMap();
        }
    }
}
